﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using SubWayElevatorPower.BUS;
using SubWayElevatorPower.Models;
using SubWayElevatorPower.Serial;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SubWayElevatorPower.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ElevatorController : ControllerBase
    {
        public SerialDataProcess serial = SerialServer.serial;
        private readonly IHostingEnvironment _hostingEnvironment;
        public ElevatorController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 查询初始值
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryPoint")]
        public ResponseMessage QueryPoint()
        {
            ResponseMessage message = new ResponseMessage();
            message.data = serial.QueryDetail();
            return message;
        }

        /// <summary>
        /// 关闭浏览器
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("CloseBrowser")]
        public ResponseMessage CloseBrowser()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {

                Process[] AllProcesses = Process.GetProcesses();
                foreach (var process in AllProcesses)
                {
                    string s = process.ProcessName.ToLower();
                    if (s.Contains("chromium-browse"))
                        process.Kill();
                }
                message.errcode = 0;
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "关闭浏览器异常 ";
            }
            return message;
        }

        /// <summary>
        /// 修改配置
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateConfig")]
        public ResponseMessage UpdateConfig(ConfigInfo configInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
                string text = System.IO.File.ReadAllText(filePath);

                // 修改配置项
                JObject obj = JObject.Parse(text);
                obj["ElevatorName"] = configInfo.elevatorname;
                obj["DeviceID"] = configInfo.deviceid;
                obj["Temperature"] = configInfo.temperaturethreshold;

                // 重新写入appsettings.json
                string result = obj.ToString();
                System.IO.File.WriteAllText(filePath, result);
                serial.Init();
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "修改配置异常 ";
            }
            return message;
        }

        /// <summary>
        /// 查询配置
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryConfig")]
        public ResponseMessage QueryConfig()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ConfigInfo configInfo = new ConfigInfo();
                JsonConfigHelper jsonConfigHelper = new JsonConfigHelper("appsettings.json");
                string ele_name = jsonConfigHelper["ElevatorName"];
                string deviceid = jsonConfigHelper["DeviceID"];
                string Temperature = jsonConfigHelper["Temperature"];
                configInfo.elevatorname = ele_name;
                configInfo.deviceid = deviceid;
                configInfo.temperaturethreshold = Temperature;
                message.data = configInfo;
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "修改配置异常 ";
            }
            return message;
        }

        /// <summary>
        /// 设置设备编号
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("SetDeviceId")]
        public ResponseMessage SetDeviceId(int id)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                if (SerialDataProcess.ele_detail.Count != 1)
                {
                    message.errcode = 1;
                    message.errmsg = "非单梯模式，不可设置";
                }
                else
                {
                    string cmd = serial.GetSetCmd(id);
                    bool result = SerialDataProcess.SendListMsg(cmd);
                    Wait(100);
                    result = SerialDataProcess.SendListMsg("FF 03 00 0F 00 01 A1 D7");
                    if (!result)
                    {
                        message.errcode = 1;
                        message.errmsg = "设置失败";
                    }
                }
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "设置设备参数异常";
            }
            return message;
        }

        public bool Wait(int second)
        {
            try
            {
                DateTime startTime = DateTime.Now;
                while (true)
                {
                    TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
                    if (secondSpan.TotalMilliseconds > second)
                    {
                        break;
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 设置时间
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("SetTime")]
        public ResponseMessage SetTime(string date)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string command = "date -s \"" + Convert.ToDateTime(date).ToString("yyyy-MM-dd HH:mm:ss") + "\"";
                Process.Start("sudo", command);
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "设置设备参数异常";
            }
            return message;
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("Reset")]
        public ResponseMessage Reset(int deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                int index = SerialDataProcess.ele_detail.FindIndex(x => x.deviceid == deviceid);
                if (index > -1)
                {
                    SerialDataProcess.ele_detail[index].alarmTime = "";
                    SerialDataProcess.ele_detail[index].alarm_temperature = 0;
                }
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "设置设备参数异常";
            }
            return message;
        }

        /// <summary>
        /// 接纳报警
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("ReceiveAlarm")]
        public ResponseMessage ReceiveAlarm(int deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                int index = SerialDataProcess.ele_detail.FindIndex(x => x.deviceid == deviceid);
                if (index > -1)
                {
                    SerialDataProcess.ele_detail[index].alarm_flag = 0;
                }
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "接纳报警异常";
            }
            return message;
        }

        /// <summary>
        /// 查询屏保时间
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryScreenTime")]
        public ResponseMessage QueryScreenTime()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                JsonConfigHelper jsonConfigHelper = new JsonConfigHelper("appsettings.json");
                int time = Convert.ToInt32(jsonConfigHelper["Screensaver"]);

                message.data = time;
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "查询屏保时间异常 ";
            }
            return message;
        }

        /// <summary>
        /// 设置屏保时间
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("SetScreenTime")]
        public ResponseMessage SetScreenTime(int Screensaver)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
                string text = System.IO.File.ReadAllText(filePath);

                // 修改配置项
                JObject obj = JObject.Parse(text);
                obj["Screensaver"] = Screensaver;

                // 重新写入appsettings.json
                string result = obj.ToString();
                System.IO.File.WriteAllText(filePath, result);
                serial.Init();
            }
            catch (Exception)
            {
                message.errcode = 1;
                message.errmsg = "设置屏保时间异常 ";
            }
            return message;
        }
    }
}
